package com.itheima.bos.web.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.swing.text.html.HTMLDocument.HTMLReader.PreAction;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.itheima.bos.domain.base.Area;
import com.itheima.bos.service.base.AreaService;
import com.itheima.bos.utils.PinYin4jUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototye")
public class AreaAction extends ActionSupport implements ModelDriven<Area>{
	
	private static final long serialVersionUID = 1L;
	//模型驱动
	private Area area=new Area();
	@Override
	public Area getModel() {
		
		return area;
	}
	//注入业务层对象
	@Autowired
	private AreaService areaService;
	//接收上传文件
	private File file;
	
	public void setFile(File file) {
		this.file = file;
	}
	
	//批量区域数据导入
	@Action(value="area_batchImport")
	public String batchImport() throws IOException{
		//存取每一个区域对象
		List<Area>areas=new ArrayList<Area>();
		//编写解析代码逻辑
		//基于.xls格式解析HSSF
		//1.加载Execl文件对象
		HSSFWorkbook hssfWorkboot=new HSSFWorkbook(new FileInputStream(file));
		//2.读取一个sheet:根据索引读取表
		HSSFSheet sheet = hssfWorkboot.getSheetAt(0);
		//3.读取sheet中每一行
		for (Row row : sheet) {
			//一行数据 对应 一个区域对象
			if(row.getRowNum()==0){
				//第一行 跳过
				continue;//跳过本次循环进入下一次循环
			}
			//跳过空行:第一个单元格值为null或者为空时跳过
			if(row.getCell(0)==null||StringUtils.isBlank(row.getCell(0).getStringCellValue())){
				continue;
			}
			//创建区域对象
			Area area1=new Area();
			area1.setId(row.getCell(0).getStringCellValue());
			area1.setProvince(row.getCell(1).getStringCellValue());
			area1.setCity(row.getCell(2).getStringCellValue());
			area1.setDistrict(row.getCell(3).getStringCellValue());
			area1.setPostcode(row.getCell(4).getStringCellValue());
			//基于pinyin4j生成城市编码和简码
			String province=area1.getProvince();
			String city = area1.getCity();
			String district = area1.getDistrict();
			province = province.substring(0, province.length() - 1);
			city = city.substring(0, city.length() - 1);
			district = district.substring(0, district.length() - 1);
			// 简码
			String[] headArray = PinYin4jUtils.getHeadByString(province + city
					+ district);
			//拼接省市区的字的头字母字符串
			StringBuffer buffer = new StringBuffer();
			for (String headStr : headArray) {
				buffer.append(headStr);
			}
			String shortcode = buffer.toString();
			area1.setShortcode(shortcode);
			// 城市编码
			String citycode = PinYin4jUtils.hanziToPinyin(city, "");
			area1.setCitycode(citycode);
			
			
			areas.add(area1);
		}
		//调用业务层
		areaService.saveBatch(areas);
		
		return NONE;
	}
	
	//属性驱动接受客户端分页参数
	private int page;
	private int rows;
	
	public void setPage(int page) {
			this.page = page;
		}

		public void setRows(int rows) {
			this.rows = rows;
		}
		//分页查询
	@Action(value="area_pageQuery",results={@Result(name="success",type="json")})
	public String pageQuery(){
		//构造分页查询对象
		Pageable pageable=new PageRequest(page-1, rows);
		//构造条件查询对象
		Specification<Area> specifcation=new Specification<Area>() {

			@Override
			// Root 用于获取属性字段，CriteriaQuery可以用于简单条件查询，CriteriaBuilder 用于构造复杂条件查询
			public Predicate toPredicate(Root<Area> root,
					CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list=new ArrayList<Predicate>();
				if(StringUtils.isNotBlank(area.getProvince())){
					
					Predicate p1 = cb.like(root.get("province").as(String.class),
							"%"+area.getProvince()+"%");
					list.add(p1);
				}
				if (StringUtils.isNotBlank(area.getCity())) {
					Predicate p2 = cb.like(root.get("city").as(String.class),
							"%" + area.getCity() + "%");
					list.add(p2);
				}
				if (StringUtils.isNotBlank(area.getDistrict())) {
					Predicate p3 = cb.like(root.get("district")
							.as(String.class), "%" + area.getDistrict() + "%");
					list.add(p3);
				}
				
				return cb.and(list.toArray(new Predicate[0]));
			}
		};
		//调用业务层完成查询
		Page<Area> pageDate=areaService.findPageData(specifcation,pageable);
		
		Map<String, Object> result=new HashMap<String, Object>();
		result.put("total", pageDate.getTotalElements());
		result.put("rows", pageDate.getContent());
		
		//压入值栈
		ActionContext.getContext().getValueStack().push(result);
		
		
		return SUCCESS;
		
	}
	
	
	
	
	
}
